
<template>
  <div class="auto-tab">
    <scroll-view class="tab-box" scroll-x="true" scroll-with-animation :scroll-into-view="currentTabId">
      <view class="tab-item" :id="'tab' + tabItem[props.valueKey]" :class="{'tab-item-active': modelValue === tabItem[props.valueKey]}" v-for="(tabItem,tabIndex) in tabList" :key="tabItem[props.valueKey]" @click="changeTab(tabItem, tabIndex)">
        <image class="tab-icon" v-if="tabItem[props.iconKey]" :src="tabItem[props.iconKey]" />
        {{ tabItem[props.labelKey] }}
      </view>
		</scroll-view>
  </div>
</template>


<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
const props = defineProps({
  tabList: { type: Array, required: true },
  modelValue: { type: Number, default: 0 },
  valueKey: { type: String, default: 'value' },
  labelKey: { type: String, default: 'label' },
  iconKey: {type: String, default: 'iconPath' }
})

const emits = defineEmits(['update:modelValue'])

const currentTabId = ref('')
const currentTabIndex = ref(-1)

watch(() => props.modelValue, (val) => {
  currentTabIndex.value = props.tabList.findIndex(item => item.id === val)
})

/**
 * @description 切换tab
*/
function changeTab(item,index) {
  if (currentTabIndex.value === index) return
  currentTabId.value = index === 0 ? '' : `tab${props.tabList[index - 1][props.valueKey]}`
  emits('update:modelValue', item[props.valueKey])
}
</script>

<style lang="scss" scoped>
.tab-box {
  height: 80upx;
  white-space: nowrap;
  .tab-item {
    height: 66upx;
    line-height: 66upx;
    display: inline-block;
    position: relative;
    text-align: center;
    border-radius: 36upx;
    border: 1px solid transparent;
    background: #fff;
    font-size: 28upx;
    margin-left: 30upx;
    padding: 0 26upx; 
    .tab-icon {
      width: 36upx;
      height: 36upx;
      vertical-align: middle;
      margin-bottom: 6upx;
    }
  }
  .tab-item-active {
    border: 1px solid rgb(226, 62, 133);
    background-color: rgb(226, 62, 133);
    color: #fff;
  }
}
</style>